package com.iweb.controller;

import com.iweb.client.UserClient;
import com.iweb.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RequestMapping("/consumer")
@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    // 注入Feign客户端
    @Autowired
    private UserClient userClient;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping
    private List<User> findAll() {
        String url = String.format("http://provider/user");
        return restTemplate.getForObject(url, List.class);
    }


    @GetMapping("{id}")
//    @HystrixCommand(fallbackMethod = "findByIdFallback")
    public User findById(@PathVariable Long id) {
        // 通过服务名称调用
        // String url = String.format("http://provider/user/%d", id);
        // return restTemplate.getForObject(url, User.class);

        // 使用Feign客户端的方式调用
        return userClient.findById(id);
    }

    public User findByIdFallback(Long id) {
        return new User();
    }

}
